package com.wingscode.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wingscode.common.utils.PageUtils;
import com.wingscode.common.utils.Query;
import com.wingscode.modules.common.entity.UserSettingEntity;
import com.wingscode.modules.common.service.UserSettingService;
import com.wingscode.modules.sys.dao.RegionDao;
import com.wingscode.modules.sys.entity.RegionEntity;
import com.wingscode.modules.sys.service.RegionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 区域
 *
 * @author yan
 */
@Service("regionService")
public class RegionServiceImpl extends ServiceImpl<RegionDao, RegionEntity> implements RegionService {

	@Resource
	private UserSettingService userSettingService;

	@Override
    public PageUtils queryPage(Map<String, Object> params) {
		IPage<RegionEntity> page = this.page(
				new Query<RegionEntity>().getPage(params),
				new QueryWrapper<RegionEntity>()
						.eq("pid", 0)
						.orderByAsc("sort")
						.orderByDesc("id")
		);

        return new PageUtils(page);
    }
	
	@Override
	public void delete(Long[] ids){
		this.removeByIds(Arrays.asList(ids));
	}

	@Override
	public PageUtils queryChildPage(Map<String, Object> params) {
		Integer pid = Integer.parseInt((String) params.get("pid"));

		IPage<RegionEntity> page = this.page(
				new Query<RegionEntity>().getPage(params),
				new QueryWrapper<RegionEntity>()
						.eq("pid", pid)
						.orderByAsc("sort")
						.orderByDesc("id")
		);

		return new PageUtils(page);
	}

	@Override
	public List<RegionEntity> getChooseCityList(Integer userId) {
		String[] idList = null;
		List<RegionEntity> list = new ArrayList<>();

		// 获得当前登录用户的区域设置
		List<UserSettingEntity> cityList = userSettingService.list(
				new QueryWrapper<UserSettingEntity>()
						.eq("user_id", userId)
		);
		if (cityList != null && cityList.size() > 0) {
			UserSettingEntity settingEntity = cityList.get(0);
			if (settingEntity.getAreaId() != null && !settingEntity.getAreaId().isEmpty())
				idList = settingEntity.getAreaId().split(",");

			if (idList != null && idList.length > 0)
				list = this.baseMapper.getChooseCityList(idList);
		}

		return list;
	}
}
